/*
 * File:		mcf52233_sysinit.c
 * Purpose:		Reset configuration of the MCF52233
 *
 * Notes:
 */
#include "support_common.h"
#include "exceptions.h"

/********************************************************************/
void
pll_init(void)
{

//MCF_CLOCK_CCHR =0x05; // The PLL pre divider - 25MHz / 5 = 5MHz 

	/* The PLL pre-divider affects this!!! 
	 * Multiply 25Mhz reference crystal /CCHR by 12 to acheive system clock of 60Mhz
	 */

	MCF_CLOCK_SYNCR = MCF_CLOCK_SYNCR_MFD(4) | MCF_CLOCK_SYNCR_CLKSRC| MCF_CLOCK_SYNCR_PLLMODE | MCF_CLOCK_SYNCR_PLLEN ;

	while (!(MCF_CLOCK_SYNSR & MCF_CLOCK_SYNSR_LOCK))
	{
	}
}
/********************************************************************/
void
scm_init(void)
{
	/*
	 * Enable on-chip modules to access internal SRAM
	 */
	MCF_SCM_RAMBAR = (0
		| MCF_SCM_RAMBAR_BA(RAMBAR_ADDRESS)
		| MCF_SCM_RAMBAR_BDE);
}
/********************************************************************/
void __initialize_hardware(void)
{
	/*******************************************************
	*	Out of reset, the low-level assembly code calls this 
	*	routine to initialize the MCF52233 modules.
	********************************************************/

	asm 
	{
	    /* Initialize IPSBAR */
	    move.l  #__IPSBAR,d0
	       andi.l  #0xC0000000,d0 // need to mask
	    add.l   #0x1,d0
	    move.l  d0,0x40000000

	    

	    /* Initialize FLASHBAR */
	    move.l  #__FLASHBAR,d0
	       andi.l  #0xFFF80000,d0 // need to mask
	    add.l   #0x61,d0
	    movec   d0,FLASHBAR

	}
	
	
	/*
	 * Configure MCF52233DEMO LEDs
	 */
	MCF_GPIO_DDRTC = 0x0F;
	
	/* 
	* Setup interrupts from IRQ[4]) 
	*/
	
	/* Enable IRQ signals on the port */
	MCF_GPIO_PNQPAR = 0 | MCF_GPIO_PNQPAR_IRQ4_IRQ4;

	/* Set EPORT to look for rising edges */
	MCF_EPORT0_EPPAR = 0 | MCF_EPORT_EPPAR_EPPA4_LEVEL;

//	/* Clear any currently triggered events on the EPORT  */
	MCF_EPORT0_EPIER = 0 | MCF_EPORT_EPIER_EPIE4;
	
	// Define the interrupt prioirty and level for IRQ4
	 MCF_INTC0_ICR04 = 0 | MCF_INTC_ICR_IP(4) | MCF_INTC_ICR_IL(4);

	/* Enable interrupts in the interrupt controller */
	MCF_INTC0_IMRL &= ~(0
			| MCF_INTC_IMRL_INT_MASK4 
			| MCF_INTC_IMRL_MASKALL);

	MCF_GPIO_PDDPAR = 0x0F;
   
	
	/*
	 * Setup low-power mode wakeup
	 */
	MCF_PMM_LPCR = 0
			| MCF_PMM_LPCR_LPMD(MCF_PMM_LPCR_LPMD_STOP)
			| MCF_PMM_LPCR_STPMD(MCF_PMM_LPCR_STPMD_ALL_DISABLED);
	MCF_PMM_LPICR = 0 
			| (MCF_PMM_LPICR_ENBSTOP 
			| MCF_PMM_LPICR_XLPM_IPL(0x0));
	
	/* Set real time clock freq */

	MCF_CLOCK_RTCDR = 25000000;

	
	/* Set GPIO for UART0 */
    MCF_GPIO_PUAPAR = 0
        | MCF_GPIO_PUAPAR_URXD0_URXD0
        | MCF_GPIO_PUAPAR_UTXD0_UTXD0;
	
	
	pll_init();
	scm_init();	

	initialize_exceptions();
}
